package de.sendorian.app.forumArchive.finder;

import static org.hamcrest.Matchers.anything;

import org.apache.log4j.Logger;
import org.hamcrest.Matcher;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;


public abstract class FinderBase<T, U> implements Finder<T, U> {

    private static final Logger LOG = Logger.getLogger(FinderBase.class);

    protected Matcher<U> filter;


    public FinderBase() {
        this.filter = anything();
    }


    public FinderBase(Matcher<U> filter) {
        this.filter = filter;
    }


    public Finder<T, U> withFilter(Matcher<U> filter) {
        this.filter = filter;
        return this;
    }


    /**
     * Parses the Page and returns the resulting NodeList
     */
    protected NodeList parse(String url, NodeFilter filter, boolean cancelOnError) {
        NodeList page = null;
        try {
            Parser parser = new Parser(url);
            page = parser.parse(filter);
        } catch (ParserException e) {
            LOG.fatal("Error reading from url.", e);
            if (cancelOnError) {
                System.exit(-1);
            }
        }
        return page;
    }

}
